# coding: utf-8
import json
import paramiko

data = {}


def connect_ssh(ip, port, username, password, command):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, port, username, password)
    for cmd in command:
        stdin, stdout, stderr = ssh.exec_command(cmd)
        info = stdout.readlines()
        if 'lscpu' in cmd:
            cpu_data = []
            for c in info:
                c_list = c.split(':')
                # cpu_data[0].append(c_list[0].strip())
                cpu_data.append(c_list[1].strip())
                # cpu_data[c_list[0].strip()] = c_list[1].strip()
            print cpu_data
        elif 'free' in cmd:
            memory = []
            for f in info:
                f_list = f.split(':')
                if len(f_list) == 1:
                    memory.append(f.split())
                if len(f_list) == 2 and f_list[0].strip() == 'Mem':
                    memory.append(f_list[1].split())
                    # memory[f_list[0].strip()] = f_list[1].split()
            print memory
        elif 'df' in cmd:
            pass
        elif 'hostname' in cmd:
            data['hostname'] = [info[0].strip()]
        elif 'system-release' in cmd:
            data['system'] = [info[0].strip()]
        elif 'net' in cmd:
            data[info[-1].split(':')[0].strip()] = info[-1].split(':')[1].split()
            data[info[-2].split(':')[0].strip()] = info[-2].split(':')[1].split()
    data["cpu_info"] = cpu_data
    data["memory"] = memory
    print data
    with open('system_info.json', 'w') as f:
        json.dump(data, f, )
    ssh.close()


if __name__ == "__main__":
    ip = "10.1.1.102"
    port = 22
    username = "zxb"
    password = "vdin1234"
    command = ['lscpu', 'free -h', 'df -h', 'cat /etc/system-release', 'hostname', 'cat /proc/net/dev']
    connect_ssh(ip, port, username, password, command)
